import cv2

# 模型路径
model_bin = "model/MobileNetSSD_deploy.caffemodel"
config_text = "model/MobileNetSSD_deploy.prototxt"
# 类别信息
objName = ["background",
"aeroplane", "bicycle", "bird", "boat",
"bottle", "bus", "car", "cat", "chair",
"cow", "diningtable", "dog", "horse",
"motorbike", "person", "pottedplant",
"sheep", "sofa", "train", "tvmonitor"]

# 加载模型
net = cv2.dnn.readNetFromCaffe(config_text, model_bin)
# 读取测试图片
car_route=[]
point_size = 1
point_color = (0, 0, 255) # BGR
thickness = 8 # 可以为 0 、4、8
lineType = 8
frame_rate_calc = 1
freq = cv2.getTickFrequency()
def caffer_detect(frame):
    # Start timer (for calculating frame rate)
    t1 = cv2.getTickCount()
    
    image = frame
    h = image.shape[0]
    w = image.shape[1]
    # 获得所有层名称与索引
    layerNames = net.getLayerNames()
    lastLayerId = net.getLayerId(layerNames[-1])
    lastLayer = net.getLayer(lastLayerId)
    # 检测
    blobImage = cv2.dnn.blobFromImage(image, 0.007843, (300, 300), (127.5, 127.5, 127.5), True, False)
    net.setInput(blobImage)
    cv2Out = net.forward()
    font = cv2.FONT_HERSHEY_SIMPLEX
    for detection in cv2Out[0,0,:,:]:
        score = float(detection[2])
        objIndex = int(detection[1])
        if score > 0.6:
            left = detection[3]*w
            top = detection[4]*h
            right = detection[5]*w
            bottom = detection[6]*h
            cv2.rectangle(image, (int(left), int(top)+10), (int(right), int(bottom)), (0, 255, 0), thickness=2)
            cv2.putText(image, "score:%.2f, %s"%(score, objName[objIndex]),
                    (int(left), int(top) - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2, 8)
     # Calculate framerate
    t2 = cv2.getTickCount()
    time1 = (t2-t1)/freq
    frame_rate_calc= 1/time1
    cv2.putText(frame,'FPS: {0:.2f}'.format(frame_rate_calc), (10,50),font, 0.7, (255,255,0), 2)
    
    return image
